<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/1/29
 * Time: 11:09
 */

namespace App\Http\Controllers\Finance;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Model\EmployeeModel;
use App\Http\Model\FinanceLiquidationModel;
use App\Http\Model\GroupModel;
use App\Http\Model\ProjectModel;
use App\Http\Model\TechnicalCompanyFinanceModel;
use App\Http\Model\TechnicalCompanyModel;
use App\Http\Model\TechnicalGroupModel;
use App\Http\Model\WorkmanAccountsModel;
use App\Http\Model\WorkmanAssignmentModel;
use App\Http\Model\YearModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class FinanceController extends Controller
{
    /**
     * 工人工资清算
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function employeeLists(Request $request)
    {
        $rules = [
            'projectId' => 'required|integer',
            'professionId' => 'nullable|integer',
            'startTime' => 'nullable|date_format:Y-m-d',
            'endTime' => 'nullable|date_format:Y-m-d',
            'isFinish' => 'nullable|integer|in:0,1',
            'length' => 'required|integer|in:10,20,50',
            'page' => 'required|integer|min:0',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'professionId.integer' => '工种参数类型错误',
            'startTime.date_format' => '起始时间格式错误',
            'endTime.date_format' => '截止时间格式错误',
            'isFinish.integer' => '清算参数类型错误',
            'isFinish.in' => '清算参数值不正确',
            'length.required' => '获取记录条数失败',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.required' => '获取起始记录位置失败',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only(['projectId', 'professionId', 'startTime', 'endTime', 'isFinish', 'page', 'length', 'search']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $employeeModel = new EmployeeModel();
            $startTime = $param['startTime'];
            $endTime = $param['endTime'];

            //确定当前工程年度时间，搜索当前工程年度项目中的所有工人
            $yearModel = new YearModel();
            $yearInfo = $yearModel->findYear(date('Y-m-d'));
            $param['startTime'] = $yearInfo['startTime'];
            $param['endTime'] = $yearInfo['endTime'];
            $param['isManager'] = 0;
            $lists = $employeeModel->lists($param);
            $countLists = $employeeModel->countLists($param);

            //按照时间区间汇总工资
            $startTime = $startTime === '' ? $yearInfo['startTime'] : $startTime;
            $endTime = $endTime === '' ? $yearInfo['endTime'] : $endTime;

            $financeLiquidationModel = new FinanceLiquidationModel();
            foreach ($lists as $key => $l) {
                $wages = $employeeModel->wages($l->id, $startTime, $endTime);
                $lists[$key]->wage = $wages;
                $info = $financeLiquidationModel->info($l->id);
                if ($info) {
                    $lists[$key]->finishTime = $info['finishTime'];
                    $lists[$key]->settleAccount = $info['account'];
                    $lists[$key]->remark = $info['remark'];
                } else {
                    $lists[$key]->finishTime = '';
                    $lists[$key]->settleAccount = '';
                    $lists[$key]->remark = '';
                }
            }
            $this->data = $this->tableFormat($lists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 710101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * 管理人员工资清算
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function managerLists(Request $request)
    {
        $rules = [
            'projectId' => 'required|integer',
            'professionId' => 'nullable|integer',
            'yearId' => 'nullable|integer',
            'isFinish' => 'nullable|integer|in:0,1',
            'length' => 'nullable|integer|in:10,20,50',
            'page' => 'nullable|integer|min:0',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'professionId.integer' => '工种参数类型错误',
            'yearId.integer' => '工程年度参数类型错误',
            'status.integer' => '工作状态参数类型错误',
            'isFinish.required' => '获取清算参数失败',
            'isFinish.integer' => '清算参数类型错误',
            'isFinish.in' => '清算参数值不正确',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->all();
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $employeeModel = new EmployeeModel();
            $yearModel = new YearModel();
            if (isset($param['yearId']) && !empty($param['yearId'])) {
                $yearInfo = $yearModel->info(['id' => $param['yearId']]);
            } else {
                $yearInfo = $yearModel->findYear(date('Y-m-d H:i:s'));
            }
            if (empty($yearInfo)) {
                throw new ApiException('请新建工程年度', 710202);
            }
            $param['startTime'] = $yearInfo['startTime'];
            $param['endTime'] = $yearInfo['endTime'];
            $param['isManager'] = 1;
            $financeLiquidationModel = new FinanceLiquidationModel();
            $lists = $employeeModel->lists($param);
            $countLists = $employeeModel->countLists($param);
            foreach ($lists as $key => $l) {
                $wages = $employeeModel->wages($l->id);
                $lists[$key]->wage = $wages;
                $info = $financeLiquidationModel->info($l->id);
                if ($info) {
                    $lists[$key]->finishTime = $info['finishTime'];
                    $lists[$key]->settleAccount = $info['account'];
                    $lists[$key]->remark = $info['remark'];
                } else {
                    $lists[$key]->finishTime = '';
                    $lists[$key]->settleAccount = '';
                    $lists[$key]->remark = '';
                }
            }
            $this->data = $this->tableFormat($lists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 710201);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function settlement(Request $request)
    {
        $rules = [
            'id' => 'required|integer',
            'settlementAccount' => 'required|numeric',
        ];
        $message = [
            'id.required' => '获取工人参数失败',
            'id.integer' => '工人参数类型错误',
            'settlementAccount.required' => '请填写清算金额',
            'settlementAccount.numeric' => '清算金额类型错误',
        ];
        $param = $request->only(['id', 'settlementAccount', 'remark']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $employeeModel = new EmployeeModel();
            $financeLiquidationModel = new FinanceLiquidationModel();
            $data = [
                'employeeId' => $param['id'],
                'finishTime' => date('Y-m-d H:i:s'),
                'account' => $param['settlementAccount'],
                'createTime' => date('Y-m-d H:i:s'),
                'adminId' => $request->session()->get('adminId'),
                'remark' => $param['remark'],
            ];
            $financeLiquidationModel->insert($data);
            $employeeModel->update(['id' => $param['id']], ['isFinish' => 1]);
        } else {
            throw new ApiException($validator->errors()->first(), 710301);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function technicalFinance(Request $request)
    {
        $rules = [
            'length' => 'required|integer|in:10,20,50',
            'page' => 'required|integer|min:1',
        ];
        $message = [
            'length.required' => '获取记录条数失败',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.required' => '获取起始记录位置失败',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only('length', 'page', 'search');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $technicalCompanyModel = new TechnicalCompanyModel();
            $technicalGroupModel = new TechnicalGroupModel();
            $employeeModel = new EmployeeModel();
            $groupModel = new GroupModel();
            $workmanAssignmentModel = new WorkmanAssignmentModel();
            $workmanAccountsModel = new WorkmanAccountsModel();
            $lists = $technicalCompanyModel->lists($param);
            $countLists = $technicalCompanyModel->countLists($param);
            $curYear = (new YearModel())->findYear(date('Y-m-d H:i:s'));
            foreach ($lists as $k => $l) {
                $groupLists = $technicalGroupModel->lists(['companyId' => $l->id]);
                $workAssignmentTotal = 0;
                $workAccountsTotal = 0;
                $liquidationTotal = 0;
                foreach ($groupLists as $key => $gl) {
                    if (isset($gl->groupId)) {
                        $workAssignmentTotal += $workmanAssignmentModel->getSum(['groupId' => $gl->groupId,'startTime'=>$curYear['startTime'],'endTime'=>$curYear['endTime']]);
                        $workAccountsTotal += $workmanAccountsModel->getSum(['groupId' => $gl->groupId,'startTime'=>$curYear['startTime'],'endTime'=>$curYear['endTime']]);

                    }
                }
                $liquidationTotal += TechnicalCompanyFinanceModel::where(['company_id' => $l->id])
                    ->where(function($query)use ($curYear){
                        $query->whereBetween('createTime',[$curYear['startTime'],$curYear['endTime']]);
                    })
                    ->sum('account');
                $lists[$k]->workAssignmentTotal = $workAssignmentTotal;
                $lists[$k]->workAccountsTotal = $workAccountsTotal;
                $lists[$k]->liquidationTotal = $liquidationTotal;
            }
            $this->data = $this->tableFormat($lists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 711001);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function technicalGroupFinance(Request $request)
    {
        $rules = [
            'companyId' => 'required|integer',
            'length' => 'required|integer|in:10,20,50',
            'page' => 'required|integer|min:1',
        ];
        $message = [
            'companyId.required' => '获取专业施工队参数失败',
            'companyId.integer' => '专业施工队参数类型错误',
            'length.required' => '获取记录条数失败',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.required' => '获取起始记录位置失败',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only('length', 'page', 'companyId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $technicalGroupModel = new TechnicalGroupModel();
            $workmanAssignmentModel = new WorkmanAssignmentModel();
            $workmanAccountsModel = new WorkmanAccountsModel();
            $financeLiquidationModel = new FinanceLiquidationModel();

            $groupLists = $technicalGroupModel->lists(['companyId' => $param['companyId']]);
            $countLists = $technicalGroupModel->countLists(['companyId' => $param['companyId']]);

            foreach ($groupLists as $key => $gl) {
                $workAssignmentTotal = 0;
                $workAccountsTotal = 0;
                $liquidationTotal = 0;

                if (isset($gl->groupId)) {
                    $workAssignmentTotal += $workmanAssignmentModel->getSum(['groupId' => $gl->groupId]);
                    $workAccountsTotal += $workmanAccountsModel->getSum(['groupId' => $gl->groupId]);
                }
//                $liquidationTotal += $financeLiquidationModel->getSum(['employeeId' => $el]);

                $groupLists[$key]->workAssignmentTotal = $workAssignmentTotal;
                $groupLists[$key]->workAccountsTotal = $workAccountsTotal;
                $groupLists[$key]->liquidationTotal = $liquidationTotal;
            }
            $this->data = $this->tableFormat($groupLists, $countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 711101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @author wanghongrui 20210806
     */
    public function technicalProjectFinance(Request $request)
    {
        $rules = [
            'groupId' => 'required|integer',
            'length' => 'required|integer|in:10,20,50',
            'page' => 'required|integer|min:1',
        ];
        $message = [
            'groupId.required' => '获取专业施工班组参数失败',
            'groupId.integer' => '专业施工班组参数类型错误',
            'length.required' => '获取记录条数失败',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.required' => '获取起始记录位置失败',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only('length', 'page', 'groupId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $technicalGroupModel = new TechnicalGroupModel();
            $workmanAssignmentModel = new WorkmanAssignmentModel();
            $workmanAccountsModel = new WorkmanAccountsModel();
            $technicalGroup = DB::table('technical_group')->where('id',$param['groupId'])->first();
            $projectLists = DB::table('project')->where('status',1)->get()->toArray();

            foreach ($projectLists as $key => $project){
                $workAssignmentTotal = 0;
                $workAccountsTotal = 0;
                if (isset($technicalGroup->groupId)) {
                    $workAssignmentTotal += $workmanAssignmentModel->getSum(['groupId' => $technicalGroup->groupId,'projectId'=>$project->id]);
                    $workAccountsTotal += $workmanAccountsModel->getSum(['groupId' => $technicalGroup->groupId,'projectId'=>$project->id]);
                }
                $projectLists[$key]->workAssignmentTotal = $workAssignmentTotal;
                $projectLists[$key]->workAccountsTotal = $workAccountsTotal;
            }
        } else {
            throw new ApiException($validator->errors()->first(), 711101);
        }
        return $this->ajaxResult($this->code, $this->msg, $projectLists);
    }

    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @author wanghongrui 20210806
     */
    public function saveTechnicalCompanyAccount(Request $request)
    {
        $rules = [
            'id' => 'required|integer',
            'account' => 'required|numeric',
        ];
        $message = [
            'id.required' => '获取专业施工队参数失败',
            'id.integer' => '专业施工队参数类型错误',
            'account.required' => '获取结款金额失败',
            'account.numeric' => '结款金额参数类型错误',
        ];
        $param = $request->only('id', 'account');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminId = $request->session()->get('adminId');
            $account = new TechnicalCompanyFinanceModel();
            $account->company_id = $param['id'];
            $account->account = $param['account'];
            $account->adminId = $adminId;
            $account->createTime = date('Y-m-d H:i:s');
            $account->save();
        } else {
            throw new ApiException($validator->errors()->first(), 711101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }
}